package example.springboot.controller;

import example.springboot.common.Result;
import example.springboot.dto.PageRequest;
import example.springboot.dto.PageResult;
import example.springboot.dto.WordDTO;
import example.springboot.entity.Word;
import example.springboot.service.FavoriteWordService;
import example.springboot.service.WordService;
import example.springboot.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @Author 董熠涛
 * @Date 2025/6/16 20:22
 */
@RestController
@RequestMapping("/api/words")
@CrossOrigin
public class WordApiController {

    @Autowired
    private WordService wordService;

    @Autowired
    private FavoriteWordService favoriteWordService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 获取单词列表（分页）
     */
    @GetMapping
    public Result<PageResult<WordDTO>> getWordList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String search) {
        try {
            PageRequest pageRequest = new PageRequest();
            pageRequest.setPage(page);
            pageRequest.setSize(size);
            pageRequest.setSearch(search);
            
            PageResult<WordDTO> result = wordService.getWordList(pageRequest);
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取单词列表失败：" + e.getMessage());
        }
    }

    /**
     * 查看单词详情
     */
    @GetMapping("/{id}")
    public Result<Word> getWordById(@PathVariable Integer id) {
        try {
            Word word = wordService.findById(id);
            if (word == null) {
                return Result.error("单词不存在");
            }
            return Result.success(word);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取单词详情失败：" + e.getMessage());
        }
    }

    /**
     * 添加生词（收藏单词）
     */
    @PostMapping("/favorite")
    public Result<Map<String, Object>> addFavorite(
            HttpServletRequest request,
            @RequestBody Map<String, Integer> data) {
        try {
            // 从token获取用户ID
            Integer userId = getUserIdFromRequest(request);
            if (userId == null) {
                return Result.error("未登录");
            }

            Integer wordId = data.get("wordId");
            if (wordId == null) {
                return Result.error("单词ID不能为空");
            }

            // 验证单词是否存在
            Word word = wordService.findById(wordId);
            if (word == null) {
                return Result.error("单词不存在");
            }

            // 调用Service添加收藏
            boolean success = favoriteWordService.addFavorite(userId, wordId);
            if (success) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", true);
                result.put("message", "添加成功");
                return Result.success("添加成功", result);
            } else {
                return Result.error("添加失败");
            }
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("添加生词失败：" + e.getMessage());
        }
    }

    /**
     * 删除生词（取消收藏）
     * @param id 单词ID（不是收藏记录ID）
     */
    @DeleteMapping("/favorite/{id}")
    public Result<String> removeFavorite(
            HttpServletRequest request,
            @PathVariable Integer id) {
        try {
            // 从token获取用户ID
            Integer userId = getUserIdFromRequest(request);
            if (userId == null) {
                return Result.error("未登录");
            }

            // 调用Service删除收藏（根据用户ID和单词ID）
            boolean success = favoriteWordService.removeFavoriteByWordId(userId, id);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败，该单词未在生词本中");
            }
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除生词失败：" + e.getMessage());
        }
    }

    /**
     * 获取收藏单词列表
     */
    @GetMapping("/favorite")
    public Result<List<WordDTO>> getFavoriteWords(HttpServletRequest request) {
        try {
            // 从token获取用户ID
            Integer userId = getUserIdFromRequest(request);
            if (userId == null) {
                return Result.error("未登录");
            }

            // 调用Service获取收藏列表
            List<WordDTO> words = favoriteWordService.getFavoriteWords(userId);
            
            return Result.success(words);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取收藏单词失败：" + e.getMessage());
        }
    }

    /**
     * 从请求中获取用户ID
     */
    private Integer getUserIdFromRequest(HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            if (token == null || token.isEmpty()) {
                return null;
            }

            return jwtUtil.getUserIdFromToken(token);
        } catch (Exception e) {
            return null;
        }
    }
}

